﻿using IntelligentStorWpfApp.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using IntelligentStorWpfApp.Controller;
using Microsoft.VisualBasic;

namespace IntelligentStorWpfApp.View
{
    /// <summary>
    /// CabinetWindow.xaml 的交互逻辑
    /// </summary>
    public partial class CabinetWindow : Window
    {
        
        public CabinetWindow()
        {
            InitializeComponent();
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            //this.Topmost = true;
        }
        public string productId { get; set; }
        private PositionController pc;
        private StatusController statusControl;
        private ProductController prodControl;
        private LinkProductPositionController lppControl;

        private void CabinetWindow_Loaded(object sender, RoutedEventArgs e)
        {
            pc = new PositionController();
            statusControl = new StatusController();
            prodControl = new ProductController();
            lppControl = new LinkProductPositionController();
            lblLoginMessage.Text= App.user.UserName + ",欢迎你！";
            //this.Title =this.Title+": " + App.user.UserName + ",欢迎你！";
            showCabinet();
        }

        /// <summary>
        /// show 柜子
        /// </summary>
        private void showCabinet()
        {
            DataTable dt = pc.getCabinetNums();
            for(int i=0;i<dt.Rows.Count;i++)
            {
                TreeViewItem item = new TreeViewItem();
                item.DataContext = dt.Rows[i][0];
                item.Header = dt.Rows[i][0].ToString()+"号柜";
                item.Selected += treeView_Selected;
                trMain.Items.Add(item);
            }
            if(trMain.Items.Count>0)
            {
                ((TreeViewItem)trMain.Items[0]).IsSelected = true;
            }
        }

        private void treeView_Selected(object sender, RoutedEventArgs e)
        {
            TreeViewItem tritem = (TreeViewItem)sender;
            showPositions(Convert.ToInt32(tritem.DataContext));
        }

        private void showPositions(int cabinetNum)
        {

            List<Position> listpos = pc.getPositions(cabinetNum);
            addButtons();
            foreach (var item in gridBtns.Children)
            {
                Button bt = item as Button;
                var query = listpos.Where(c=>c.PositionNum.Equals(bt.DataContext)).ToList();
                if(query.Count>0)
                {
                    bt.IsEnabled = true;
                    if(query[0].Status>0)
                    {
                        
                        bt.Background = System.Windows.Media.Brushes.Red;
                    }
                    else
                    {
                        bt.Background = System.Windows.Media.Brushes.LawnGreen;
                    }
                    bt.Tag = query[0];
                    bt.Click += Bt_Click;
                }

            }
        }

        private void Bt_Click(object sender, RoutedEventArgs e)
        {
            Button currentBt = (Button)sender;
            Position pTag = (Position)currentBt.Tag;
            ContextMenu aMenu = new ContextMenu();
            MenuItem scMenu = new MenuItem();
            if(pTag.Status > 0)
            {
                scMenu.Header = "出库";

            }
            else
            {
                scMenu.Header = "入库";
            }
            scMenu.Click += ScMenu_Click;
            scMenu.Tag = pTag;
            aMenu.Items.Add(scMenu);
            aMenu.IsOpen = true;
        }

        private void ScMenu_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mItem = (MenuItem)sender;
            Position p = (Position)mItem.Tag;
            Status status = new Status();
            status.PositionId = p.Id;
            if (p.Status > 0)
            {
                status.StoreStatus = 0;
            }
            else
            {
                status.StoreStatus = 1;
            }
            bool result = false;
            if (!string.IsNullOrEmpty(productId))
            {
                LinkProductPosition temlpp = lppControl.GetDraftLinkByPostionId(p.Id);
                MessageBoxResult mbr;
                if (temlpp != null)
                {
                    mbr = MessageBox.Show("产品"+temlpp.ProductId+"已经设定在"+temlpp.SetTime.ToString()+"入库,继续入库此设定将不生效。是否继续入库?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                }
                else
                {
                    mbr = MessageBox.Show("确认入库?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                }
                if(mbr==MessageBoxResult.Yes)
                {
                    bool delresult = lppControl.DeleteDraftLinkByPositionId(p.Id);
                    result = statusControl.UpdateStatus(status, productId);
                }
                else
                {
                    return;
                }
            }
            else
            {
                LinkProductPosition temlpp = lppControl.GetDraftLinkByPostionId(p.Id);
                MessageBoxResult mbr;
                if (temlpp != null)
                {
                    mbr = MessageBox.Show("产品" + temlpp.ProductId + "已经设定在" + temlpp.SetTime.ToString() + "出库,继续出库此设定将不生效。是否继续出库?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                }
                else
                {
                    mbr = MessageBox.Show("确认出库?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                }
                if (mbr == MessageBoxResult.Yes)
                {
                    bool delresult = lppControl.DeleteDraftLinkByPositionId(p.Id);
                }
                else
                {
                    return;
                }
                if (p.Status > 0)
                {
                    result = statusControl.UpdateStatus(status);
                }
                else
                {
                    string inputStr = Interaction.InputBox("请输入产品编号:", "输入产品编号", "", 100, 50);
                    if (!string.IsNullOrEmpty(inputStr))
                    {
                        if (!prodControl.GetProductByProductId(inputStr))
                        {
                            MessageBox.Show("产品" + inputStr + "不存在!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                        else
                        {
                            result = statusControl.UpdateStatus(status, inputStr);
                        }
                    }
                    else
                    {
                        return;
                    }
                }
            }
            if (!result)
            {
                if (p.Status > 0)
                    MessageBox.Show("出库失败!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                    MessageBox.Show("入库失败!", "Error", MessageBoxButton.OK,MessageBoxImage.Error);
            }
            else
            {
                showPositions( Convert.ToInt32(((TreeViewItem) trCabinet.SelectedItem).DataContext));
            }
            
        }

        /*
        public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {
            //Bitmap bitmap = icon.ToBitmap();

            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            if (!DeleteObject(hBitmap))
            {
                throw new System.ComponentModel.Win32Exception();
            }
            return wpfBitmap;

        }
        */

        /// <summary>
        /// 增加箱号
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        private void addButtons()
        {
            gridBtns.Children.Clear();
            gridBtns.Height = 300;
            gridBtns.Width = 400;
            //动态设定gridGame为4行4列
            for (int i = 0; i < 4; i++)
            {
                RowDefinition rd = new RowDefinition();
                rd.Height = GridLength.Auto;
                gridBtns.RowDefinitions.Add(rd);

                ColumnDefinition cd = new ColumnDefinition();
                cd.Width = GridLength.Auto;
                gridBtns.ColumnDefinitions.Add(cd);
            }
            int a = 1;
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    Button btn = new Button();
                    btn.Content =a;
                    btn.DataContext = a;
                    btn.Width = 70;
                    btn.Height = 50;
                    btn.Margin = new Thickness(5);
                    btn.IsEnabled = false;
                    btn.Background = System.Windows.Media.Brushes.LightGray;
                    Grid.SetRow(btn, i);
                    Grid.SetColumn(btn, j);
                    gridBtns.Children.Add(btn);
                    a++;
                }
            }
            a = 0;
        }

        private void AddMenuItem_Click(object sender, RoutedEventArgs e)
        {
            AddCabinet addcabinetWin = new AddCabinet();
            addcabinetWin.ShowDialog();
        }
    }
}
